/*
 * Copyright 2010 Katsunori Koyanagi
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package sweezy.anim.updater.filters
{
	import flash.display.DisplayObject;
	import flash.filters.BitmapFilter;
	import flash.utils.Dictionary;

	internal class FilterUpdaterBase
	{

		private var _filterInfos:Dictionary;

		public function FilterUpdaterBase()
		{
			_filterInfos = new Dictionary(true);
		}

		protected function getFilter(obj:DisplayObject, type:Class):BitmapFilter
		{
			var filterInfo:Dictionary;
			if (obj in _filterInfos)
			{
				filterInfo = _filterInfos[obj];
			}
			else
			{
				_filterInfos[obj] = filterInfo = new Dictionary(true);
			}

			var filterObj:Object = filterInfo;
			var filter:BitmapFilter = null;
			if (type in filterInfo)
			{
				filter = (filterInfo[type] as type) as BitmapFilter;
			}
			if (filter === null)
			{
				var filters:Array = obj.filters;
				if (filters !== null)
				{
					for (var i:int = 0, len:uint = filters.length; i < len; i++)
					{
						if (filters[i] is type)
						{
							filter = filters[i];
							break;
						}
					}
				}
				if (filter === null)
				{
					filter = new type();
					if (filters === null)
					{
						filters = [];
					}
					filters.push(filter);
					obj.filters = filters;
				}

				filterInfo[type] = filter;
			}

			return filter;
		}
	}
}
